/**
 * @Description: 菜单管理
 * @author dazer
 * @date 2019/3/5 下午17:21
 */
import React, { Fragment } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  BackTop,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import setTitle from '@/decorator/setTitle';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '@/components/ourslook/BaseForm';
import ETable from '@/components/ourslook/ETable';
import { getWebPath } from '../../utils/request';
import uiUtils, { hasPermission } from '../../utils/uiUtils';
import styles from '../../utils/ourslook.less';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// @setTitle('代码生成器~')
@connect(() => ({}))
class Generator extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => `${index + 1}`,
    },
    { title: '表名', dataIndex: 'tableName', width: 288, align: 'left', sorter: true },
    { title: '引擎', dataIndex: 'engine', width: 100, align: 'center', sorter: true },
    { title: '数据条数', dataIndex: 'rows', width: 100, align: 'right', sorter: true },
    { title: '表备注', dataIndex: 'tableComment', align: 'left', sorter: false },
    { title: '创建时间', dataIndex: 'createTime', width: 190, align: 'center', sorter: true },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Generator.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      //其他属性下面书写
    };
  }

  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'tableName',
      label: '表名',
      placeholder: '表名、表备注、拼音',
    },
    {
      type: 'INPUT',
      field: 'tableComment',
      label: '表备注',
      placeholder: '表备注',
    },
    {
      type: 'DATE_RANGE',
      field: 'createDate',
      label: '创建、更新时间',
      placeholder: ['创建、更新时间', ''],
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  generator = () => {
    const selectedRows = this.state.selectedRows;
    const tableNames = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      tableNames.push(selectedRows[i].tableName);
    }

    window.location.href = getWebPath(
      `/sys/generator/code?tables=${encodeURIComponent(JSON.stringify(tableNames))}`
    );
    //window.location.href = getWebPath(`/sys/generator/code?tables=${JSON.stringify(ids)}`);//复现400报错
  };

  generatorWord = () => {
    const selectedRows = this.state.selectedRows;
    const tableNames = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      tableNames.push(selectedRows[i].tableName);
    }

    window.location.href = getWebPath(
      `/sys/generator/documentWord?tableNames=${encodeURIComponent(tableNames)}`
    );
  };

  generatorExcel = () => {
    const selectedRows = this.state.selectedRows;
    const tableNames = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      tableNames.push(selectedRows[i].tableName);
    }

    window.location.href = getWebPath(
      `/sys/generator/documentExcel?tableNames=${encodeURIComponent(tableNames)}`
    );
  };

  generatorPdf = () => {
    const selectedRows = this.state.selectedRows;
    const tableNames = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      tableNames.push(selectedRows[i].tableName);
    }

    window.location.href = getWebPath(
      `/sys/generator/documentPdf?tableNames=${encodeURIComponent(tableNames)}`
    );
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath('/sys/generator/list')}`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      }
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="code"
              onClick={this.generator}
              hidden={!hasPermission('sys:generator:code')}
            >
              生成代码
            </Button>
            <Button
              type="primary"
              icon="file-word"
              {...style}
              onClick={this.generatorWord}
              hidden={!hasPermission('sys:generator:code')}
            >
              导出word
            </Button>
            <Button
              type="primary"
              icon="file-excel"
              {...style}
              onClick={this.generatorExcel}
              hidden={!hasPermission('sys:generator:code')}
            >
              导出excel
            </Button>
            <Button
              type="primary"
              icon="file-pdf"
              {...style}
              onClick={this.generatorPdf}
              hidden={!hasPermission('sys:generator:code')}
            >
              导出Pdf
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="menuId"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 910 }}
            />
          </div>

          <BackTop />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Generator;
